package com.sunshine.lnuplus.internet

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Looper
import androidx.fragment.app.FragmentManager
import com.sunshine.lnuplus.view.DialogWithoutView
import es.dmoral.toasty.Toasty
import okhttp3.*
import org.json.JSONException
import org.jsoup.Jsoup
import java.io.IOException

/**
 * Created by sunshine on 2020/3/5
 */
class CheckUpdate(
    private val context: Context,
    private val supportFragmentManager: FragmentManager,
    private val isAbout: Boolean
) {
    private val UPDATEVERSION = context.packageManager.getPackageInfo(context.packageName, 0).versionName
    private val UPDATECODE = context.packageManager.getPackageInfo(context.packageName, 0).versionCode

    init {
        val url = "http://www.iyuji.cn/iyuji/s/VUlpZG1WZ3A2alo2OWtxZThadHU2QT09/1575180597291559"
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(url).build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                if(isAbout){
                    Looper.prepare()
                    Toasty.info(context, "没有网络连接").show()
                    Looper.loop()
                }
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                resolveUpdate(response.body!!.string())
            }
        })
    }

    private fun resolveUpdate(functionData: String) {
        val document = Jsoup.parse(functionData)
        val elements = document.select("p")
        val updateStrings = elements.toString().replace("<p>", "").replace("</p>", "").replace("/n","\n").split("#")
        val positive = DialogInterface.OnClickListener { _, _ ->
            try {
                val str = "market://details?id=com.sunshine.lnuplus"
                val localIntent = Intent(Intent.ACTION_VIEW, Uri.parse(str))
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                localIntent.`package` = "com.coolapk.market"
                context.startActivity(localIntent)
            } catch (e: Exception) {
                try {
                    val str = "market://details?id=com.sunshine.lnuplus"
                    val localIntent = Intent(Intent.ACTION_VIEW, Uri.parse(str))
                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(localIntent)
                }catch (e : Exception){
                    try {
                        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.coolapk.com/apk/com.sunshine.lnuplus")))
                    }catch (e: Exception){
                        Toasty.error(context, "打开浏览器失败").show()
                    }
                }
            }
        }
        val negative = DialogInterface.OnClickListener { _, _ ->
            try {
                context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.coolapk.com/apk/com.sunshine.lnuplus")))
            }catch (e: Exception){
                Toasty.error(context, "打开浏览器失败").show()
            }
        }

        //如果该版本比发布版本小则检查更新
        try{
            if(UPDATECODE < updateStrings[2].toInt()){
                DialogWithoutView.newInstance(
                    "Shine课程表有新版本啦",
                    "当前版本：${UPDATEVERSION}\n最新版本：${updateStrings[0]}\n\n${updateStrings[1]}\n\n如果你不想收到更新提醒，请移步至我->软件设置，取消勾选主界面提示更新。",
                    true,
                    positive,
                    negative).show(supportFragmentManager, "update")
            }else if(isAbout){
                Looper.prepare()
                Toasty.success(context, "已经是最新版本").show()
                Looper.loop()
            }
        }catch (e: Exception){
            Looper.prepare()
            Toasty.error(context, "$e 检查更新失败").show()
            Looper.loop()
        }
    }
}